package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.dto.role.RoleDTO;
import com.qk.entity.Role;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@SuppressWarnings("all")
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public PageResult<Role> listRoles(RoleDTO roleDto) {
        PageHelper.startPage(roleDto.getPage(), roleDto.getPageSize());
        List<Role> roles = roleMapper.selectByPage(roleDto);
        Page<Role> page = (Page<Role>)  roles;
        return PageResult.<Role>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void addRole(Role role) {
        boolean hasNull = BeanUtil.hasNullField(role, "id","remark","updateTime","createTime" );
        if (hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insert(role);
    }

    @Override
    public void deleteRole(Integer id) {
        if (Objects.isNull( id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        roleMapper.deleteById(id);
    }

    @Override
    public void updateRole(Role role) {
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.update(role);
    }

    @Override
    public Role getById(Integer id) {
        if (Objects.isNull(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return roleMapper.getById(id);
    }

    @Override
    public List<Role> getAllRoles() {
        List<Role> roles = roleMapper.getAllRoles();
        return roles;
    }

}
